<template>
  <div>
      <div v-if="onlyshow">
          <el-input v-model="showtxt" :readonly="true" :disabled="disabled" ></el-input>
      </div>
      <div v-else>
          <el-input v-if="isTextarea" :style="{width:width}" type="textarea" :rows="textarearow"  :placeholder="mydataLabel" ref="ddlmainSelect" :disabled="disabled"  @clear="clearinput"  @dblclick.native="popbigtab" @blur="inputblur" :clearable="clearable" v-model="ddlvalue" :readonly="readonly" key="1">
              <i v-if="disabled" class="el-input__icon el-icon-menu" slot="suffix"></i>
              <i v-else @click="popbigtab" class="el-input__icon el-icon-menu" slot="suffix"></i>
          </el-input>
          <el-select v-else-if="datalength<20 && !disabled" :placeholder="mydataLabel" :style="{width:width}" @change="changevt" :disabled="disabled" @dblclick.native="popbigtab" @keyup.space.native="popbigtab" :clearable="clearable" ref="ddlmainSelect" v-model="ddlvalue" :popper-class="pclass" :filterable="filterable" @visible-change="visibleChange($event)">
              <el-option :key="item.hidkey" :label="item.hidname" :value="item.hidkey" v-for="item in seloptions">
                  <span style="float: left">{{ showcode?item.hidkey : item.hidname }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{  showcode?item.hidname : item.hidkey}}</span>
              </el-option>
          </el-select>
          <el-select v-else-if="datalength<20 && disabled" :placeholder="mydataLabel" :style="{width:width}" @change="changevt" :disabled="disabled" ref="ddlmainSelect" v-model="ddlvalue" :popper-class="pclass" :filterable="filterable">
              <el-option :key="item.hidkey" :label="item.hidname" :value="item.hidkey" v-for="item in seloptions">
                  <span style="float: left">{{ showcode?item.hidkey : item.hidname }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{  showcode?item.hidname : item.hidkey }}</span>
              </el-option>
          </el-select>
          <el-input v-else :style="{width:width}" :placeholder="mydataLabel" ref="ddlmainSelect" :disabled="disabled" @input.native="ddlmainSelect_input" @keyup.enter.native="ddlmainSelect_keyupenter" @keyup.native="ddlmainSelect_keyupenter" @clear="clearinput" @keyup.space.native="popbigtab" @dblclick.native="popbigtab" @blur="inputblur" :clearable="clearable" v-model="showtxt" :readonly="readonly" key="1">
              <i v-if="disabled" class="el-input__icon el-icon-menu" slot="suffix"></i>
              <i v-else @click="popbigtab" class="el-input__icon el-icon-menu" slot="suffix"></i>
          </el-input>
      </div>

      <el-dialog :append-to-body="appendtobody" top="40px" :close-on-click-modal="false" :title="mydataLabel" :visible.sync="dialogTableVisible">
          <el-container style="height: 500px; border: 1px solid #eee">
              <el-main style="overflow: hidden;">
                  <el-input @input="autosearch" @keydown.native="searchkeydown" placeholder="快速检索" prefix-icon="el-icon-search" ref="qcodeinput" style="width:300px;" v-model="qcode"></el-input>
                  <el-button @click="btnok" icon="el-icon-circle-check" style="margin-left:10px;margin-top:3px;">确定</el-button>
                  <el-button @click="dialogTableVisible = false" style="margin-top:3px;" icon="el-icon-circle-close">取消</el-button>
                  <el-button style="float:right;margin-top:3px;" @click="refreshdata" icon="el-icon-refresh">刷新数据</el-button>
                  <vxe-grid :columns="tableColumn" :pager-config="tablePage" :data="tableData" @cell-dblclick="vxselect" :loading="loading" border height="461px" highlight-current-row highlight-hover-row show-header-overflow="tooltip" show-overflow="tooltip" ref="ddlcommonTable" resizable size="mini" stripe style="margin-top:5px"></vxe-grid>
              </el-main>
          </el-container>
      </el-dialog>
      <el-dialog width="900px" v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false" :title="dataname" :visible.sync="dialogMultipleVisible" :destroy-on-close="true">
          <rm-SqlMultiple :leftOption="Loptions" :rightOption="Roptions"  name="hidkey" @change="Closenewdialog"></rm-SqlMultiple>
      </el-dialog>
  </div>
</template>
<script>
export default {
  props: { width: { type: String, default: "200px" }, value: [Number, String], datatype: { type: String }, instrid: { type: Number }, appendtobody: { type: Boolean, default: true }, dataname: { type: String }, kindno: { type: String }, disabled: { type: Boolean }, readonly: { type: Boolean, default: false }, onlyshow: { type: Boolean, default: false }, pclass: { type: String }, showcode: { type: Boolean, default: false }, beforeChange: { type: Function }, filterable: { type: Boolean }, clearable: { type: Boolean, default: true }, labgroupid: { type: Number, default: 0 }, sysno: { type: String, default: "" }, isadmincanall: { type: String, default: "0" }, ishidelabel: { type: Boolean, default: false } ,irrelevant: { type: String },ygflag:{type:String ,default:"0"},isMultiple: { type: Boolean, default: false },isTextarea: { type: Boolean, default: false },textarearow:{type: String, default: "1"},colfilter:{type: String,default:""}},
  watch: {
      value(newVal) {
          this.myvalue = newVal;
          if (this.datalength < 20) {
              //小于20行显示下拉框
              if (newVal) {
                  this.ddlvalue = newVal.toString();
                  if (this.onlyshow) {
                      //只做显示显示名称
                      this.showtxt = "";
                      if (newVal != "") {
                          let cData = this.fulldata.Data.filter((item) => item.hidkey.toString().toUpperCase().trim() == newVal.toString().toUpperCase().trim());
                          if (cData.length > 0) {
                              this.showtxt = cData[0].hidname;
                          } else {
                              this.showtxt = newVal.toString().trim();
                          }
                      }
                  }
              } else {
                  this.ddlvalue = "";
                  this.showtxt = "";
              }
          } else {
              //大于20行显示输入框
              // this.myvalue = newVal;
              this.showtxt = "";
              if (newVal && newVal != "") {
                  //增加toString修正当传入控件的值为数值型使用trim()出错的bug
                  let cData = this.fulldata.Data.filter((item) => {
                      if (!!item.hidkey) {
                          return item.hidkey.toString().toUpperCase().trim() == newVal.toString().toUpperCase().trim();
                      }
                  });
                  if (cData.length > 0) {
                      this.showtxt = cData[0].hidname;
                  } else {
                      this.showtxt = newVal.toString().trim();
                  }
              }
          }
      },
      myvalue(newVal) {
          // console.log(" myvalue cccccccccccc", newVal);
          this.$emit("input", newVal);
          //this.value = newVal;
      },
      datatype(newVal) {
          this.loadAllData();
      },
      instrid(newVal) {
          this.loadAllData();
      },
      kindno(newVal) {
          this.loadAllData();
      },
      sysno(newval) {
          this.loadAllData();
      },
      labgroupid() {
          this.loadAllData();
      },
      isadmincanall() {
          this.loadAllData();
      },
  },
  data() {
      return {
          qcode: "",
          myvalue: this.value,
          showtxt: "",
          ddlvalue: this.value,
          mydataLabel: this.ishidelabel ? this.dataname : "请选择" + (this.dataname ? this.dataname : ""),
          mydatatype: this.datatype,
          mykindno: this.kindno,
          fulldata: null,
          tableColumn: [],
          tablePage: {
              pageSize: 1000,
          },
          selrow: null,
          tableData: null,
          seloptions: [],
          datalength: 0,
          dialogTableVisible: false,
          loading: false,
          showirrelevant: "",
          mygflag:this.ygflag,
          dialogMultipleVisible:false,
          Loptions:[],
          Roptions:[],

      };
  },
  computed: {
      myappendtobody: function () {
          return this.appendtobody;
      },
  },
  updated() {
      // if (this.$refs.ddlcommonTable) {
      //     if (this.fulldata.Data.length > 0) {
      //         this.$refs.ddlcommonTable.setCurrentRow(this.fulldata.Data[0]);
      //     }
      // }
      if (this.$refs.qcodeinput) {
          this.$refs.qcodeinput.focus();
      }
      this.showirrelevant = this.irrelevant;
  },
  methods: {
      visibleChange(e) {
          //目的供应商改变时值的还原
          this.$emit("beforechange", this.myvalue, e);
      },
      async clearinput() {
          let execflag = true;
          // console.log("this.beforeChange ", typeof this.beforeChange);
          if (typeof this.beforeChange === "function") {
              let r = await this.beforeChange();
              if (!r) {
                  execflag = false;
              }
          }
          // console.log("execflag", execflag);
          if (execflag) {
              this.myvalue = "";
              this.$nextTick(() => {
                  this.$emit("change", "", "", "");
                  this.$emit("changeObj", {code:'', name:'', row:''});
              });
          } else {
              let cData = this.fulldata.Data.filter((item) => item.hidkey && item.hidkey.trim() == this.value);
              if (cData.length > 0) {
                  this.showtxt = cData[0].hidname;
              } else {
                  this.showtxt = this.myvalue;
              }
          }
      },

      popMultipleChk() {
          let  temp =[] ;// this.tableData.filter(m=>m.hidkey!="");
          console.log(this.fulldata);
          for (var i in  this.fulldata.Data)
          {
              let _item =  this.fulldata.Data[i];
              temp.push({
                              display: _item.hidname,
                              data: _item.hidkey,
                              inputcode:_item.inputcode
                          })
          }

        /* this.RightListOptions.push({
                              display: kvalue[1],
                              data: kvalue[0]
                          }); */

          this.Loptions=[];
          this.Roptions=[];

          if (this.myvalue != "") {
              let k = this.myvalue.split(",");
              k.forEach((item) => {
                  let ndata = temp.find((m) => m.data == item);
                  if (ndata != undefined && ndata != null) {
                      //push
                      this.Roptions.push(ndata);
                  }
              });
              temp.forEach((item) => {
                  if (k.indexOf(item.data + "") < 0) {
                      this.Loptions.push(item);
                  }
              });
          } else {
              this.Loptions = temp;
          }
          this.dialogMultipleVisible = true;
      },

      Closenewdialog(value, name,displaydata) {
         //  console.log(value);
          // console.log(displaydata) ;
             // this.searchObj[name] = value;
          if (value!="close"){
              this.ddlvalue = value;
              this.myvalue =value;
              this.$emit("change", value, displaydata, {});
              this.$emit("changeObj", {code:value, name:displaydata, row:""});
          }
          this.dialogMultipleVisible = false;
      },

      ddlmainSelect_input() {
          if (this.showtxt == "") {
              this.clearinput();
          }
      },
      async ddlmainSelect_keyupenter() {
          let c = "";
          let n = "";
          let execflag = true;
          if (typeof this.beforeChange === "function") {
              let r = await this.beforeChange();
              if (!r) {
                  execflag = false;
              }
          }
          if (execflag) {
              let cData = this.fulldata.Data;
              if (this.showtxt != "") {
                  cData = cData.filter((item) => item.hidkey == this.showtxt || item.hidname == this.showtxt);
                  if (cData.length > 0) {
                      this.showtxt = cData[0].hidname;
                      c = cData[0].hidkey;
                      n = cData[0].hidname;
                  }
              }
              this.myvalue = c;
              this.$nextTick(() => {
                  this.$emit("change", c, n, cData[0]);
                  this.$emit("changeObj", {code:c, name:n, row:cData[0]});
              });
          } else {
              let cData = this.fulldata.Data.filter((item) => item.hidkey && item.hidkey.trim() == this.myvalue);
              if (cData.length > 0) {
                  this.showtxt = cData[0].hidname;
              } else {
                  this.showtxt = this.myvalue;
              }
          }
      },
      changeactiverow: function (cindex) {
          var row = this.$refs.ddlcommonTable.getCurrentRecord();
          var ridx = this.$refs.ddlcommonTable.getRowIndex(row);
          var newidx = ridx + cindex;
          if (newidx < 0) newidx = 0;
          if (newidx >= this.tableData.length) {
              newidx = 0;
          }
          var newrow = this.tableData[newidx];
          this.$refs.ddlcommonTable.setCurrentRow(newrow);
          // this.$refs.ddlcommonTable.scrollToRow(newrow);
          this.$nextTick(() => {
              if (this.$refs.ddlcommonTable) {
                  var crow = this.$refs.ddlcommonTable.getCurrentRecord();
                  this.$refs.ddlcommonTable.scrollToRow(crow);
              }
          });
      },

      searchkeydown: async function (evt) {
          if (evt.keyCode == 13) {
              setTimeout(async () => {
                  let execflag = true;
                  if (typeof this.beforeChange === "function") {
                      let r = await this.beforeChange();
                      if (!r) {
                          execflag = false;
                      }
                  }
                  if (execflag) {
                      // console.log("按了回车");
                      this.myvalue = this.$refs.ddlcommonTable.getCurrentRecord().hidkey;
                      if (this.myvalue) {
                          this.dialogTableVisible = false;
                          this.$nextTick(() => {
                              this.$refs.ddlmainSelect.focus();
                              this.$emit("change", this.$refs.ddlcommonTable.getCurrentRecord().hidkey, this.$refs.ddlcommonTable.getCurrentRecord().hidname, this.$refs.ddlcommonTable.getCurrentRecord());
                              this.$emit("changeObj", {code:this.$refs.ddlcommonTable.getCurrentRecord().hidkey, name:this.$refs.ddlcommonTable.getCurrentRecord().hidname, row:this.$refs.ddlcommonTable.getCurrentRecord()});
                          });
                      }
                  }
              }, 1);
          } else if (evt.keyCode == 40) {
              var cindex = 1;
              this.changeactiverow(cindex);
          } else if (evt.keyCode == 38) {
              var cindex = -1;
              this.changeactiverow(cindex);
          }
      },
      autosearch: function (evt) {
          if (evt.keyCode != 13 && evt.keyCode != 40 && evt.keyCode != 38) {
              this.filterdata();
          }
      },
      btnok: async function () {
          let execflag = true;
          if (typeof this.beforeChange === "function") {
              let r = await this.beforeChange();

              if (!r) {
                  execflag = false;
              }
          }
          if (execflag) {
              if(this.isTextarea) this.myvalue = this.$refs.ddlcommonTable.getCurrentRecord().hidname;
              else this.myvalue = this.$refs.ddlcommonTable.getCurrentRecord().hidkey;

              this.dialogTableVisible = false;
              this.$nextTick(() => {
                  this.$refs.ddlmainSelect.focus();
                  this.$emit("change", this.$refs.ddlcommonTable.getCurrentRecord().hidkey, this.$refs.ddlcommonTable.getCurrentRecord().hidname, this.$refs.ddlcommonTable.getCurrentRecord());
                  this.$emit("changeObj", {code:this.$refs.ddlcommonTable.getCurrentRecord().hidkey, name:this.$refs.ddlcommonTable.getCurrentRecord().hidname, row:this.$refs.ddlcommonTable.getCurrentRecord()});
              });
          }
          // this.$emit("returnBack", this.myvalue);
      },
      inputblur: function () {
          this.$emit("blur", this.showtxt);
      },
      popbigtab: function (evt) {
          if (this.disabled) {
              return;
          }
          if  (this.isMultiple)
          {
             // console.log("双击多选");
              this.popMultipleChk();
              return ;
          }
          this.qcode = "";
          this.$refs.ddlmainSelect.blur();
          this.dialogTableVisible = true;
          this.$nextTick(() => {
              this.$refs.qcodeinput.focus();
          });
          this.filterdata();
      },
      changevt: async function (evt) {
          let execflag = true;
          if (typeof this.beforeChange === "function") {
              let r = await this.beforeChange();
              if (!r) {
                  execflag = false;
              }
          }
          if (execflag) {
              let cData = this.fulldata.Data;
              var evtname = "";
              if (evt && evt != "0" && evt != "") {
                  cData = cData.filter((item) => item.hidkey == evt);
                  if (cData && cData.length > 0) {
                      evtname = cData[0].hidname;
                  }
              }
              this.myvalue = evt;
              this.$nextTick(() => {
                  this.$refs.ddlmainSelect.focus();
                  this.$emit("change", evt, evtname, cData[0]);
                  this.$emit("changeObj", {code:evt, name:evtname, row:cData[0]});
              });
          } else {
              this.ddlvalue = this.myvalue;
          }
          // this.$emit("returnBack", evt);
      },
      setcol() {
          // var collist = [];
          // for (let i = 0, len = this.fulldata.Cols.length; i < len; i++) {
          //     const item = this.fulldata.Cols[i];
          //     let colitem = {
          //         field: item.field,
          //         title: item.title,
          //         width: item.width
          //     };
          //     collist.push(colitem);
          // }
          this.tableColumn = this.fulldata.Cols; // collist;
      },
      filterdata() {
          let cData = this.fulldata.Data;
          if (cData) {
              try {
                  if (this.qcode != "") {

                   if(this.colfilter){

                      cData = cData.filter((item) => (!!item.hidkey ? item.hidkey.toUpperCase().indexOf(this.qcode.toUpperCase()) > -1 : false) || (!!item.hidname ? item.hidname.toUpperCase().indexOf(this.qcode.toUpperCase()) > -1 : false) || (!!item.inputcode ? item.inputcode.toUpperCase().indexOf(this.qcode.toUpperCase()) > -1 : false)|| (!!item.colfilter ? item.colfilter.toUpperCase().indexOf(this.qcode.toUpperCase()) > -1 : false));
                      }
                      else{
                      //增加!!item.hidkey……修正当数据存在null而导致的整个搜索失效的问题
                      cData = cData.filter((item) => (!!item.hidkey ? item.hidkey.toUpperCase().indexOf(this.qcode.toUpperCase()) > -1 : false) || (!!item.hidname ? item.hidname.toUpperCase().indexOf(this.qcode.toUpperCase()) > -1 : false) || (!!item.inputcode ? item.inputcode.toUpperCase().indexOf(this.qcode.toUpperCase()) > -1 : false));
                      }
                  }
                  let haveall = cData.find((m) => m.hidkey == "All" ||  m.hidkey == "-1" );
                  if (this.irrelevant == "groupShowIrrelevant"){
                      //检验工作组显示无关
                      let progroup = { 检验工作组名称: "所有检验工作组", 检验工作组代码: "All", 所属检验科室代码: "",所属检验科室:"",拼音码:"",检验工作组ID:"", hidkey: "-1", hidname: "所有检验工作组", inputcode: "WG", seq: 0 };
                      if (!haveall) cData.splice(0, 0, progroup);
                  }

                  // debugger;
                  // if(this.datatype=="bactpurpose" && this.ygflag=="1"){
                  //     cData=cData.filter((item)=>item.ygflag ==this.ygflag);
                  // }

                  if (cData.length > 0) {
                      this.selrow = cData[0];
                  } else {
                      this.selrow == null;
                  }
                  this.tableData = cData;
                  this.$nextTick(() => {
                      if (this.$refs.ddlcommonTable) {
                          if (this.selrow) {
                              this.$refs.ddlcommonTable.setCurrentRow(this.selrow);
                          }
                      }
                  });
              } catch (e) {
                  console.log("erro", e);
              }
          }
      },
      refreshdata() {
          //localStorage.removeItem("RMCOMDDL_" + this.mydatatype + "_" + this.mykindno + "_" + this.instrid);
          let key = "RMCOMDDL_" + (this.mydatatype ? this.mydatatype : "") + "_" + (this.mykindno ? this.mykindno : "") + "_" + (this.instrid ? this.instrid : "") + "_" + (this.labgroupid ? this.labgroupid : 0) + "_" + (this.sysno ? this.sysno : "") + "_" + (this.isadmincanall  ? this.isadmincanall : "");
          let comdata = this.$ddldata.common_data;

          let dlldataitem = comdata.find((t) => t.key == key);
          if (dlldataitem) {
              comdata.splice(comdata.indexOf(dlldataitem), 1);
              this.$ddldata.common_data = comdata;
          }
          this.loadAllData();
      },
      loadAllData: function () {
          this.loading = true;
          //localStorage.removeItem("RMCOMDDL_" + this.mydatatype + "_" + this.mykindno + "_" + this.instrid);
          // let ccdata = JSON.parse(localStorage.getItem("RMCOMDDL_" + this.mydatatype + "_" + this.mykindno + "_" + this.instrid));
          let key = "RMCOMDDL_" + (this.mydatatype ? this.mydatatype : "") + "_" + (this.mykindno ? this.mykindno : "") + "_" + (this.instrid ? this.instrid : "") + "_" + (this.labgroupid ? this.labgroupid : 0) + "_" + (this.sysno ? this.sysno : "") + "_" + (this.isadmincanall ? this.isadmincanall : "");
          // console.log("key", key);
          let ccdata = null;
          let comdata = this.$ddldata.common_data;
          if (comdata) {
              let dlldataitem = comdata.find((t) => t.key == key);
              if (dlldataitem && dlldataitem.val) {
                  ccdata = dlldataitem.val;
              } else {
                  ccdata = null;
              }
          }
          // console.log("ccdata", ccdata);
          if (!ccdata) {
              this.$tool
                  .request({
                      url: "ucent/ddl",
                      method: "post",
                      data: {
                          action: this.mydatatype,
                          kindno: this.mykindno,
                          instrid: this.instrid,
                          labgroupid: this.labgroupid,
                          sysno: this.sysno,
                          isadmincanall: this.isadmincanall,
                          mygflag:this.mygflag,
                      },
                  })
                  .then((res) => {
                      this.fulldata = res;
                      this.setcol();
                      try {
                          // localStorage.setItem("RMCOMDDL_" + this.mydatatype + "_" + this.mykindno + "_" + this.instrid, JSON.stringify(res));
                          this.$ddldata.common_data.push({ key: key, val: res });
                      } catch (e) {}
                      this.datalength = this.fulldata.Data.length;

                      if (this.datalength < 20) {
                          this.seloptions = this.fulldata.Data;
                          this.ddlvalue = this.value;
                      } else {
                          if (this.value != "") {
                              let cData = this.fulldata.Data;
                              cData = cData.filter((item) => item.hidkey == this.value);
                              if (cData.length > 0) {
                                  this.showtxt = cData[0].hidname;
                              }
                          }
                      }
                      this.loading = false;
                      this.filterdata();
                  })
                  .catch((e) => {
                      this.loading = false;
                      this.myvalue = e;
                      //console.log("erro", e);
                  });
          } else {
              this.fulldata = ccdata;
              this.setcol();
              this.datalength = this.fulldata.Data.length;
              if (this.datalength < 20) {
                  this.seloptions = this.fulldata.Data;
                  if (this.value) {
                      this.ddlvalue = this.value.toString();
                  }
              } else {
                  if (this.value != "") {
                      let cData = this.fulldata.Data;
                      cData = cData.filter((item) => item.hidkey == this.value);
                      if (cData.length > 0) {
                          this.showtxt = cData[0].hidname;
                      }
                  }
              }
              this.loading = false;
          }
      },
      vxselect: async function (data, evt) {
          let execflag = true;
          if (typeof this.beforeChange === "function") {
              let r = await this.beforeChange();

              if (!r) {
                  execflag = false;
              }
          }
          if (execflag) {
              if(this.isTextarea) this.myvalue = data.row.hidname;
              else this.myvalue = data.row.hidkey;
              this.dialogTableVisible = false;
              this.$nextTick(() => {
                  this.$refs.ddlmainSelect.focus();
                  this.$emit("change", data.row.hidkey, data.row.hidname, data.row);
                  this.$emit("changeObj", {code:data.row.hidkey, name:data.row.hidname, row:data.row});
              });
          }
      },
      focus() {
          this.$refs.ddlmainSelect.focus();
      },
  },
  mounted() {
      this.loadAllData();
  },
  updated() {
      if (this.$refs.ddlcommonTable) {
          let tableBodyElem = this.$refs.ddlcommonTable.$refs.xTable.$refs.tableBody.$el;
          tableBodyElem.scrollTop = 1;
          this.$nextTick(() => {
              tableBodyElem.scrollTop = 0;
          });
      }
  },
};
</script>
<style scoped>
.el-main {
  padding: 0;
}
</style>
